package com.kyxx.topics.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.TextUtil;
import com.kyxx.topics.utils.Tools;
import com.kyxx.topics.view.MyCommonTitle;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2016/10/7.
 */
public class UserBindMobile extends Activity implements View.OnClickListener {
    private MyCommonTitle myCommonTitle;
    private EditText edUsername, edCode;
    private TextView tvTitle, btnSendCode, btnSubmit;
    private String userMobile, code;
    private int type, threeType;//type为1位綁定手机,type为2为换绑手机,    threeType为1是QQ  threeType为2是微信
    private String openId, nickname, avatar;//threeType为1是QQ的ID,昵称,头像  threeType为2是wx的ID,昵称,头像
        private static String APPKEY = "1770c6f012dda";
    private static String APPSECRET = "8196301ef118a8d76c717c190c51ecfa";
//    private static String APPKEY = "1835003f02938";
//    private static String APPSECRET = "f608d269bbd4c9cb4f9b21ac810001cd";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getIntExtra("type", -1);//type为1位綁定手机,type为2为换绑手机,
        threeType = getIntent().getIntExtra("threeType", -1);//threeType为1是QQ  threeType为2是微信
        openId = getIntent().getStringExtra("openId");//第三方ID   D558B7DE74E0203EB7810652D9B476CE
        nickname = getIntent().getStringExtra("nickname");//昵称   栀薇花
        avatar = getIntent().getStringExtra("avatar");//头像  http://q.qlogo.cn/qqapp/1105645339/D558B7DE74E0203EB7810652D9B476CE/40
        setContentView(R.layout.activity_user_bind_mobile);

        // 初始化短信验证
        SMSSDK.initSDK(this, APPKEY, APPSECRET);
        EventHandler eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eh);

        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        myCommonTitle = (MyCommonTitle) findViewById(R.id.aci_myTitle);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        edUsername = (EditText) findViewById(R.id.ed_mobile);// 用户名
        edCode = (EditText) findViewById(R.id.ed_code);// 验证码
        btnSendCode = (TextView) findViewById(R.id.btn_send_code);// 发送验证码
        btnSubmit = (TextView) findViewById(R.id.btn_submit);// 确定
        if (type == 1) {
            myCommonTitle.setTitle("绑定手机");
            tvTitle.setText("为了您账户的安全，请绑定手机号");
            btnSubmit.setText("立即绑定");
        } else if (type == 2) {
            myCommonTitle.setTitle("更换手机号码");
            tvTitle.setText("更换手机号码");
            btnSubmit.setText("立即更换");
        }
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (edUsername.getText().toString().length() > 0) {
                    btnSendCode.setBackgroundResource(R.drawable.bg_circle_bule);
                    btnSendCode.setEnabled(true);
                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        };
        edUsername.addTextChangedListener(watcher);
        btnSubmit.setOnClickListener(this);
        btnSendCode.setOnClickListener(UserBindMobile.this);
    }

    @Override
    public void onClick(View view) {
        userMobile = edUsername.getText().toString().trim();
        code = edCode.getText().toString().trim();
        switch (view.getId()) {
            case R.id.btn_send_code:
                if (!TextUtil.isMobile(userMobile)) {
                    Tools.toast(UserBindMobile.this, "手机号码格式不正确！");
                    return;
                }
                /* 发送手机验证码 */
                btnSendCode.setOnClickListener(null);
                new MyCount(60000, 1000).start();// 一分钟倒计时
                SMSSDK.getVerificationCode("86", userMobile);
                break;
            case R.id.btn_submit:// 提交
                if (StringUtil.isEmpty(userMobile)) {
                    Tools.toast(UserBindMobile.this, "手机号码不能为空！");
                    return;
                }
                if (!TextUtil.isCode(code, 4)) {
                    Tools.toast(UserBindMobile.this, "验证码格式不正确！");
                    return;
                }
                SMSSDK.submitVerificationCode("86", userMobile, code);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        SMSSDK.unregisterAllEventHandler();
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            Log.e("result", "result=" + result);
            Log.e("event", "event=" + event);
            if (result == SMSSDK.RESULT_COMPLETE) {
                // 短信注册成功后，返回MainActivity,然后提示新好友
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                    Tools.toast(UserBindMobile.this, "提交验证码成功");
                    submitData(type, threeType);
//                    if (type.equals("register")) {
//                        registerNewUser();
//                    } else if (type.equals("forget_pwd")) {
//                        resetPassWord();
//                    }
                    // uu_password.setFocusable(true);
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    Tools.toast(UserBindMobile.this, "验证码已经发送");
                }
            } else {
//                MyRequestDailog.closeDialog();
                ((Throwable) data).printStackTrace();
                // int resId = getStringRes(UserRegisterActivity.this,
                // "smssdk_network_error");
                Tools.toast(UserBindMobile.this,
                        event == SMSSDK.EVENT_GET_VERIFICATION_CODE ? "验证码频繁，请稍后再试！" : "验证码错误");
                // if (resId > 0) {
                // Tools.toast(UserRegisterActivity.this, resId + "");
                // }
            }
        }
    };

    /**
     * 正常注册后登录 提交信息，调用登录接口 "id": "15", "username": "", "pwd":
     * "e3ceb5881a0a1fdaad01296d7554868d", "mobile": "18660992783", "addtime":
     * "1463471681", "nickname": "", "avatar": ""
     */
    private void submitData(final int type, final int threeType) {//type为1 绑定手机  type为2 更换手机   threeType为第三方登录跳转过来判断是QQ或者是WX
//        $mobile = $_POST['mobile'];
//        $weixin = $_POST['weixin'];
//        $qq = $_POST['qq'];
//        $nickname = $_POST['nickname'];
//        $avatar = $_POST['avatar'];
        RequestParams params = new RequestParams();
        params.put("mobile", userMobile);
        if (type == 1) {//type=2为绑定手机
            if (threeType == 1) {//threeType=1为QQ跳转过来绑定手机
                params.put("qq", openId);//D558B7DE74E0203EB7810652D9B476CE
                params.put("nickname", nickname);//栀薇花
                params.put("avatar", avatar);//http://q.qlogo.cn/qqapp/1105645339/D558B7DE74E0203EB7810652D9B476CE/40
            } else if (threeType == 2) {//threeType=1为WX跳转过来绑定手机
                params.put("weixin", openId);
                params.put("nickname", nickname);
                params.put("avatar", avatar);
            }
        } else if (type == 2) {//type=2为换绑手机
            params.put("uid", BaseApp.getModel().getId());
        }
        RestClient.post(type == 1 ? UrlUtils.BINDMOBILE : UrlUtils.CHANGEBINDMOBILE, params, UserBindMobile.this, new ResponseListener(UserBindMobile.this, true) {

            @Override
            public void success(int arg0, Header[] arg1, org.json.JSONObject jsonObject) {
                if (type == 1) {
                    Tools.toast(UserBindMobile.this, "绑定成功！");
//                    "uid": "9",      "nickname": "小菜",      "sex": "0",       "birthday": "0000-00-00",        "qq": "",       "score": "0",    "login": "1",
//                     "reg_ip": "0",       "reg_time": "1476079952",      "last_login_ip": "0",      "last_login_time": "0",     "status": "1",       "cover_id": "0",
//                      "thumb": "http://q.qlogo.cn/qqapp/1105645339/D558B7DE74E0203EB7810652D9B476CE/40",       "mobile": "15963995336"
                    try {
                        String uid = jsonObject.getJSONObject("data").getString("uid");
                        BaseApp.getModel().setId(jsonObject.getJSONObject("data").getString("uid"));
                        String nickname = jsonObject.getJSONObject("data").getString("nickname");
                        BaseApp.getModel().setNickname(jsonObject.getJSONObject("data").getString("nickname"));
                        String mobile = jsonObject.getJSONObject("data").getString("mobile");
                        BaseApp.getModel().setMobile(jsonObject.getJSONObject("data").getString("mobile"));
                        String avatar = jsonObject.getJSONObject("data").getString("thumb");
                        BaseApp.getModel().setAvatar(jsonObject.getJSONObject("data").getString("thumb"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else if (type == 2) {
                    Tools.toast(UserBindMobile.this, "手机更换成功！");
                    BaseApp.getModel().setMobile(userMobile);
                }
                setResult(47);
                finish();
            }

            @Override
            public void failed(int arg0, Header[] arg1, org.json.JSONObject jsonObject) {
                super.failed(arg0, arg1, jsonObject);
                if (type == 1) {
                    Tools.toast(UserBindMobile.this, "绑定失败！");
                } else if (type == 2) {
                    Tools.toast(UserBindMobile.this, "手机更换失败！");
                }
            }
        });

    }

    /* 定义一个倒计时的内部类 */
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            btnSendCode.setText("获取验证码");
            btnSendCode.setOnClickListener(UserBindMobile.this);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btnSendCode.setText(millisUntilFinished / 1000 + "秒");
        }
    }
}
